import config from './config'

function formatNumber (n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function request (target, data, type) {
  const token =
      data !== null && typeof data.token !== 'undefined' && data.token !== null
        ? data.token
        : null
  return new Promise((resolve, reject) => {
    wx.request({
      url: config.BASE_URL + target,
      data: data,
      method: type,
      header: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/json;charset=UTF-8',
        Authorization: token
      },
      success: function (res) {
        resolve(res.data)
      },
      fail: function (res) {
        reject(res.data)
      }
    })
  })
}

export function formatTime (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}

export default {
  formatNumber,
  formatTime
}
